package com.example.musicplayer

import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.media.MediaPlayer
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.View
import androidx.activity.ComponentActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import java.io.IOException
import android.Manifest
import android.Manifest.permission
import android.Manifest.permission.READ_MEDIA_AUDIO
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import android.os.IBinder
import android.widget.Button
import android.widget.SeekBar
import android.widget.TextView
import androidx.annotation.RequiresApi
import kotlin.concurrent.thread

class MainActivity : ComponentActivity(), ServiceConnection {
    val TAG = "MainActivity"

    var binder:MusicService.MusicBinder? = null
    val Channel_ID = "my channel"
    val Notification_ID = 1


    @SuppressLint("MissingInflatedId")
    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (ContextCompat.checkSelfPermission(this, READ_MEDIA_AUDIO) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, arrayOf(READ_MEDIA_AUDIO),0)
        }else{
            startMusicService()
        }
        val seekBar= findViewById<SeekBar>(R.id.seekBar)
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener{
            override fun onProgressChanged(
                seekBar: SeekBar,
                progress: Int,
                fromUser: Boolean
            ){
                if(fromUser){
                    binder?.currentPosition = progress
                }
            }
            override fun onStartTrackingTouch(seekBar: SeekBar) {}
            override fun onStopTrackingTouch(seekBar: SeekBar) {}
        })



        val nono = findViewById<Button>(R.id.button6)
        nono.setOnClickListener {
            val notificationManager :NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            val builder: Notification.Builder
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val notificationChannel = NotificationChannel(Channel_ID, "test", NotificationManager.IMPORTANCE_HIGH)
                notificationManager.createNotificationChannel(notificationChannel)
                builder = Notification.Builder(this, Channel_ID)
            } else {
                builder = Notification.Builder(this)
            }

            val intent = Intent(this,MainActivity::class.java)
            val pendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)

            val notification:Notification=builder.setSmallIcon(R.drawable.ic_notification)
                .setContentTitle("music name")
                .setContentText(binder!!.musicName)
                .setPriority(Notification.PRIORITY_HIGH)
                .setContentIntent(pendingIntent)
                .build()
            notificationManager.notify(Notification_ID, notification)
        }
    }


    private fun startMusicService(){
        val intent = Intent(this,MusicService::class.java)
        intent.putExtra(MusicService.Commond,1)
        startService(intent)
        bindService(intent,this, Context.BIND_AUTO_CREATE)
    }

    fun onPlay(view: View) {
        val intent = Intent(this,MusicService::class.java)
        intent.putExtra(MusicService.Commond,1)
        startService(intent)
    }

    fun onPause(view: View) {
        val intent = Intent(this,MusicService::class.java)
        intent.putExtra(MusicService.Commond,2)
        startService(intent)
    }
    fun onStop(view: View) {
        val intent = Intent(this,MusicService::class.java)
        intent.putExtra(MusicService.Commond,3)
        startService(intent)
    }
    fun onNext(view: View) {
        val intent = Intent(this,MusicService::class.java)
        intent.putExtra(MusicService.Commond,4)
        startService(intent)
    }
    fun onPrev(view: View){
        val intent = Intent(this,MusicService::class.java)
        intent.putExtra(MusicService.Commond,5)
        startService(intent)
    }


    private fun onRequestPermissionResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        startMusicService()
    }


    override fun onDestroy() {
        super.onDestroy()
        unbindService(this) //解除绑定服务
    }

    override fun onServiceDisconnected(name: ComponentName?) {
        binder = null
    }

    @SuppressLint("SetTextI18n")
    override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
        binder = service as MusicService.MusicBinder
        thread{
            while(binder != null){
                Thread.sleep(1000)
                runOnUiThread{
                    val seekBar = findViewById<SeekBar>(R.id.seekBar)
                    val textView_mn = findViewById<TextView>(R.id.textView_mn)
                    val textView_count = findViewById<TextView>(R.id.textView_count)

                    seekBar.max = binder!!.duration
                    seekBar.progress = binder!!.currentPosition
                    textView_mn.text = binder!!.musicName
                    textView_count.text="${binder!!.currentIndex+1}/${binder?.size}"
                }
            }
        }
    }
}




